import sys
import json
from collections import defaultdict

def generate1mm(seq):
    mismatch = {'A':'CTG', 'T':'ACG', 'C':'ATG', 'G':'ATC'}
    mm = set()
    [mm.add(seq[0:i]+j+seq[i+1:]) for i, e in enumerate(seq) for j in mismatch[e]]
    return mm

with open(sys.argv[1]) as js:
    pjs = json.load(js)

    sampleReads = defaultdict(int)
    sampleIndex = defaultdict(str)
    undetermined = defaultdict(int)

    for lane in pjs['ConversionResults']:
        for sample in lane['DemuxResults']:
            sampleReads[sample['SampleId']] += sample['NumberReads']
            sampleIndex[sample['SampleId']] = sample['IndexMetrics'][0]['IndexSequence']
        undetermined['Undetermined'] += lane['Undetermined']['NumberReads']

    otherBarcode = defaultdict(int)
    bcs = set()
    for lane in pjs['UnknownBarcodes']:
        for k, v in lane['Barcodes'].items():
            otherBarcode[k] += v
            bcs.add(k)

    print('sampleID\tindex\treadsNumber\t\tmax1misIndex\tmax1misNumber\tsum1misNumber')
    print(f'Undetermined\tUndetermined\t{undetermined["Undetermined"]:,}')
    for k, v in sampleReads.items():
        idx = sampleIndex[k]
        idxSets = generate1mm(idx)
        combined = idxSets & bcs
        maxnum = 0
        mmidx = ''
        if combined:
            summm = 0
            for i in combined:
                if maxnum < otherBarcode[i]:
                    maxnum = otherBarcode[i]
                    mmidx = i
                summm += otherBarcode[i]
            print(f'{k}\t{idx}\t{v:,}\t\t{mmidx}\t{maxnum:,}\t{summm:,}')
        else:
            print(f'{k}\t{idx}\t{v:,}')
    print()

    n = 0
    print('UnknownBarcodes\treadsNumber')
    for k, v in sorted(otherBarcode.items(), key=lambda x: x[1], reverse=True):
        n += 1
        if n < 21:
            print(f'{k}\t{v:,}')

